﻿using ApiLogic.BaseLogic;
using System;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.SessionState;

namespace BackstageWeb.App_Start.Helper
{
    public class LoginCheckHttpHelper : IHttpModule, IRequiresSessionState
    {
        void IHttpModule.Init(HttpApplication context)
        {
            context.AcquireRequestState += new EventHandler(context_AuthenticateRequest);
        }

        /// <summary>
        /// Session验证拦截
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="e"></param>
        private void context_AuthenticateRequest(object obj, EventArgs e)
        {
            HttpApplication context = (HttpApplication)obj;
            if (Regex.IsMatch(context.Request.Url.LocalPath.ToLower(), "^/api/"))
            {
                //登陆验证Session
                ApiLoginValidate(context);
            }
        }

        /// <summary>
        /// Api登陆
        /// </summary>
        /// <param name="context"></param>
        private void ApiLoginValidate(HttpApplication context)
        {
            if (Regex.IsMatch(context.Request.Url.LocalPath.ToLower(), "^/api/login") ||
                Regex.IsMatch(context.Request.Url.LocalPath.ToLower(), "^/api/registered") ||
                Regex.IsMatch(context.Request.Url.LocalPath.ToLower(), "^/api/main") ||
                (Regex.IsMatch(context.Request.Url.LocalPath.ToLower(), "^/api/grouppurchase/loadlist") && !context.Request.QueryString.ToString().Contains("token")))
            {
                return;
            }

            //要求验证
            if (!context.Request.QueryString.ToString().Contains("token"))
            {
                ClientSession.AddClientInfo(null);
                return;
            }

            ////通过token获取用户信息
            //IClientInfoService customerService = UnityCIContainer.Instance.GetService<IClientInfoService>();
            //ClientTicket client = customerService.loadClientByCode(context.Request.QueryString["token"].ToString().ToUpper());
            //if (client != null)
            //{
            //    ClientSession.addClientInfo(client);
            //}
            //else
            //{
            //    context.CompleteRequest();
            //}
        }

        void IHttpModule.Dispose()
        { }
    }
}